import { Controller, Get, Res } from '@nestjs/common';
import { map } from 'rxjs/operators'
import { Response } from 'express';
import xlsx from 'node-xlsx';
import { MoutaiService } from './moutai.service';
import * as stream from 'stream';
const urlencode = require('urlencode');

@Controller('download')
export class DownloadController {
  constructor(private readonly moutaiService: MoutaiService) {}

  @Get()
  download(@Res() res: Response) {
    return this.moutaiService.getNetProfit()
      .pipe(
        map(({title, dates, values}) => {
          const buffer = xlsx.build([{name: title, data: [dates, values]}]);
          const readStream = new stream.PassThrough();
          readStream.end(buffer)
          let name = urlencode(title + '_' + (+new Date()) + '.xlsx', "utf-8");
          res.set({
            'Content-Type': 'application/octet-stream',
            'Content-Disposition':  "attachment; filename* = UTF-8''" + name
          });
          readStream.pipe(res);
        })
      );
  }
}
